﻿using MesGLApp.BLL;
using MesGLApp.BLL.Mes;
using MesGLApp.DAL.MesDB;
using MesGLApp.DAL.MesDTO;
using MesGLApp.DAL.RoleDTO;
using Smobiler.Core;
using Smobiler.Core.Controls;
using Smobiler.Plugins.TTS;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Web.UI.WebControls;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Xml.Linq;
using static MesGLApp.View.Search.SiteIPQCDetail;
using static System.Net.Mime.MediaTypeNames;
using Label = Smobiler.Core.Controls.Label;
using Panel = Smobiler.Core.Controls.Panel;
using TextBox = Smobiler.Core.Controls.TextBox;

namespace MesGLApp.View.Search
{
    partial class SiteIPQCFrm : Smobiler.Core.Controls.MobileForm
    {
        private ProdProcScanControler _ctrl1 = new ProdProcScanControler();
        private ExcepOrderControler _ctrl = new ExcepOrderControler();
        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private SiteInfo _curr_site = null;
        TargetProdProcessDTO tmpTarget = null;
        private SqlSugarClient Db = SqlSugares.GetInstance();
        BaseControler bs = new BaseControler();
        private List<StatusInfo> _status_list = new List<StatusInfo>();
        int IPQCXMNumber;
        private List<string> options;
        public SiteIPQCFrm() : base()
        {
            InitializeComponent();
            btnScan.ResourceID = "barcode";
            comboBox1.Text = "无异常";
        }

        private void btnClose_Press(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 打开站点选择列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSite_Press(object sender, EventArgs e)
        {
            if (this._site_list != null && this._site_list.Count > 0)
            {
                this.popSite.ShowDialog();
            }
            else
            {
                MessageBox.Show("您的权限不能操作任何站点！", "提示");
            }
        }
        /// <summary>
        /// 选择站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void popSite_Selected(object sender, EventArgs e)
        {
            this.btnSite.Text = this.popSite.Selection.Text;
            if (this._site_list != null && this._site_list.Count > 0)
            {
                var query = this._site_list.Where(s => s.SiteName == this.popSite.Selection.Text);
                if (query != null && query.Count() > 0)
                {
                    this._curr_site = query.First<SiteInfo>();
                    this.button2.Text = _curr_site.SiteName;
                }
                else
                {
                    this.button2.Text = "请选择站点  >";
                }
            }
            var list = Db.Context.SqlQueryable<object>($@"select
	            * 
            from
	            site_info
            where
	            id={this._curr_site.ID} or parent_id = {this._curr_site.ID}").ToList();
            string SiteIDStr = "";
            if (list.Count == 1)
            {
                dynamic dylist = list;
                int parentid = dylist[0].parent_id;
                var list1 = Db.Context.SqlQueryable<object>($@"select
	                * 
                from
	                site_info
                where
	                parent_id = {parentid} or id = {parentid}").ToList();
                dynamic dylist1 = list1;
                list.AddRange(list1);
                dylist = list;
                for (int i = 0; i < list.Count; i++)
                {
                    SiteIDStr += dylist[i].id + ",";
                }
            }
            SiteIDStr = SiteIDStr.Substring(0, SiteIDStr.Length - 1);
            var IPQCList = Db.Context.SqlQueryable<object>($@"select distinct
	            qc_name
            from
	            site_qc
            where
                site_id in ({SiteIDStr})").ToList();
            dynamic dyIPQCList = IPQCList;
            IPQCXMNumber = IPQCList.Count;//记录多少个项目 
            int Y = 0;
            DataSource.Items.Clear();
            DataTable table = new DataTable();
            table.Columns.Add("qc_name", typeof(System.String));
            table.Columns.Add("Value", typeof(System.String));
            for (int i = 0; i < dyIPQCList.Count; i++)
            {
                table.Rows.Add(dyIPQCList[i].qc_name);
                DataSource.Items.Add(new Name_Value(dyIPQCList[i].qc_name, ""));
            }

            SiteIPQCDetail siteIPQCDetail = new SiteIPQCDetail();
            listView1.Rows.Clear();     //清除数据
            if (table.Rows.Count > 0)    //绑定数据源
            {
                listView1.DataSource = table;
                listView1.DataBind();
            }


            //for (int i = 0; i < IPQCList.Count; i++)
            //{
            //    Label lbl = new Label
            //    {
            //        Name = "lbl" + i,
            //        Width = 150,  // 设置宽度
            //        Height = 25,  // 设置高度
            //        Text = dyIPQCList[i].qc_name,//项目名称
            //        FontSize = 15,
            //        Location = new System.Drawing.Point(5, Y)  // 设置坐标(x, y)
            //    };
            //    // 创建一个新的 TextBox 控件
            //    TextBox txt = new TextBox
            //    {
            //        Name = "txt" + i,
            //        Width = 190,  // 设置宽度
            //        Height = 25,  // 设置高度
            //        FontSize = 15,
            //        Location = new System.Drawing.Point(100, Y)  // 设置坐标(x, y)
            //    };
            //    //把控件添加到panle3里面
            //    panel3.Controls.Add(lbl);
            //    panel3.Controls.Add(txt);

            //    Y += 30;
            //}
            var notGood = Db.Context.SqlQueryable<object>($@"select distinct
             reason
            from
              repair_reason
            where
                 site_id in ({SiteIDStr})").ToList();
            dynamic dynotGood = notGood;
            CBONotGood.Text = "";
            txtNotGood.Text = "";
            this.CBONotGood.Items.Clear();
            for (int i = 0; i < notGood.Count; i++)
            {

                this.CBONotGood.Items.Add(dynotGood[i].reason);
            }
            //if (options != null)
            //{
            //    options.Clear();
            //}
            //options = this.CBONotGood.Items;
        }
        /// <summary>
        /// 初始化可操作的站点
        /// </summary>
        private void InitSiteList()
        {
            List<int> deptIds = bs.SelectUserDept();
            this.popSite.Groups.Clear();
            _site_list = _ctrl.SearchAllSiteInfo().Where(d => deptIds.Contains(d.deptId)).ToList();
            if (this._site_list != null && this._site_list.Count > 0)
            {
                PopListGroup tmpGroup = new PopListGroup();
                foreach (var item in this._site_list.OrderBy(s => s.SiteCode))
                {
                    tmpGroup.AddListItem(item.SiteName, item.ID.ToString());
                }
                this.popSite.Groups.Add(tmpGroup);
            }
        }

        private void SiteIPQCFrm_Load(object sender, EventArgs e)
        {
            this.InitSiteList();
        }

        private void btnScan_BarcodeScanned(object sender, BarcodeResultArgs e)
        {
            if (e.Value != null && e.Value.ToString().Length > 0)
            {
                this.txtProdNumber.Text = e.Value.ToString();
            }
            tmpTarget = this._ctrl1.SearchTargetForScan(this.txtProdNumber.Text.Trim());
            if (tmpTarget == null)
            {
                MessageBox.Show("工单号不存在！");
                this.txtProdNumber.Text = "";
                return;
            }
            if (this._curr_site == null)
            {
                MessageBox.Show("请先选择站点！");
                this.txtProdNumber.Text = "";
                return;
            }
            this.label4.Text = tmpTarget.GoodsNumber;//品号
            this.OrderNumber.Text = tmpTarget.OrderQty.ToString();//工单数量
            this.ProdNumber.Text = tmpTarget.ProdQty.ToString();//投产数量
        }

        private void txtNotGood_TextChanged(object sender, EventArgs e)
        {
            string input = txtNotGood.Text.ToLower();
            List<string> filteredOptions = options.FindAll(option => option.ToLower().Contains(input));
            CBONotGood.Items.Clear();
            foreach (string option in filteredOptions)
            {
                CBONotGood.Items.Add(option);
            }
        }

        private void CBONotGood_ItemSelected(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 提交保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Press(object sender, EventArgs e)
        {
            if (this._curr_site == null)
            {
                MessageBox.Show("请选择站点！");
                this.txtProdNumber.Text = "";
                return;
            }
            if (this.label4.Text.Trim() == "")
            {
                MessageBox.Show("工单号未扫描！");
                return;
            }
            if (txtIPQCNumber.Text.ObjToDecimal() == 0)
            {
                MessageBox.Show("检验数量未填写！");
                return;
            }
            if (ProdNumber.Text.ObjToDecimal() < txtIPQCNumber.Text.ObjToDecimal())
            {
                MessageBox.Show("检验数量不能大于工单生产数量！");
                return;
            }
            if (txtIPQCNumber.Text.ObjToDecimal() < txtIPQCNotNumber.Text.ObjToDecimal())
            {
                MessageBox.Show("不良数量不能大于检验数量！");
                return;
            }
            //任意一个不良条件满足后
            if (comboBox1.Text != "无异常" || txtIPQCNotNumber.Text.ObjToDecimal() > 0 || CBONotGood.Text != "")
            {
                if (comboBox1.Text == "无异常")
                {
                    MessageBox.Show("异常情况未选择！");
                    return;
                }
                if (txtIPQCNotNumber.Text.ObjToDecimal() == 0)
                {
                    MessageBox.Show("不良数量未输入！");
                    return;
                }
                if (CBONotGood.Text == "")
                {
                    MessageBox.Show("不良描述未选择！");
                    return;
                }
            }
            //List<Dateil> listDetail = new List<Dateil>();
            //for (int i = 0; i < IPQCXMNumber; i++)
            //{
            //    TextBox txt = panel3.Controls["txt" + i] as TextBox;
            //    Label lbl = panel3.Controls["lbl" + i] as Label;
            //    listDetail.Add(new Dateil());
            //    listDetail[i].Name = lbl.Text;
            //    listDetail[i].Value = txt.Text;
            //    if (txt.Text == "")
            //    {
            //        MessageBox.Show(lbl.Text + "未填写！");
            //        txt.BorderColor = Color.Red;
            //        txt.Border = new Border(1, 1, 1, 1);
            //        return;
            //    }
            //}

            for (int i = 0; i < DataSource.Items.Count; i++)
            {
                if (DataSource.Items[i].Value == "")
                {
                    MessageBox.Show(DataSource.Items[i].Name + "未填写！");
                    return;
                }
            }

            var ThisDayNumber = Db.Context.SqlQueryable<object>($@"select
	            *
            from
	            inspect_info
            where
	            convert(char(10),create_date,120) like '{DateTime.Now.ToString("yyyy-MM-dd")}'").ToList();
            BaseUserDTO tmpUser = Client.Session["User"] as BaseUserDTO;
            string InspectNo = "IPQC" + DateTime.Today.ToString("yyyyMMdd") + (ThisDayNumber.Count + 1).ToString("D5");
            var statusList = Db.Context.SqlQueryable<object>($@"select
	            *
            from
	            status_info
            where
                id = {tmpTarget.ProdStatusID}").ToList();
            dynamic dystatus = statusList;
            int StatusID = dystatus[0].id;
            decimal IPQCNotNumber = txtIPQCNotNumber.Text.ObjToDecimal();
            string StatusValue = dystatus[0].status_value;
            try
            {
                Db.Ado.ExecuteCommand($@"insert into inspect_info values('{InspectNo}',GETDATE(),{tmpTarget.ID},'{tmpTarget.ProdNumber}','{this._curr_site.ID}'
                ,'{this._curr_site.SiteName}','{StatusID}','{StatusValue}','{tmpTarget.ProdQty}','{txtIPQCNumber.Text}','{txtIPQCNumber.Text.ObjToDecimal() - txtIPQCNotNumber.Text.ObjToDecimal()}'
                ,{IPQCNotNumber},'{textBox1.Text}','{tmpUser.user_name}',GETDATE(),'{CBONotGood.Text}','{textType.Text}','{textTM.Text}','{comboBox1.Text.ToString()}','{textUser.Text}')");
            }
            catch (Exception ex)
            {

                throw;
            }
            //新增一条异常数据
            if (comboBox1.Text != "无异常")
            {
                ProdAbnormal_Detail P1 = new ProdAbnormal_Detail();
                P1.prod_id = tmpTarget.ID;//工单ID
                P1.prod_number = tmpTarget.ProdNumber;//工单号
                P1.site_id = this._curr_site.ID;//站点ID
                P1.site_name = this._curr_site.SiteName;//站点名称
                P1.abnormal_qty = this.txtIPQCNotNumber.Text.ObjToDecimal();//异常数量
                P1.status_id = (comboBox1.Text.ToString() == "严重异常") ? 7 : 21;//普通异常21，严重7
                P1.status_name = comboBox1.Text.ToString();//异常名称
                //P1.reason_id = resultArray[1].ToInt();//异常ID
                P1.reason_name = CBONotGood.Text.ToString();//异常名称
                P1.remark = this.textBox1.Text;//备注
                P1.create_date = DateTime.Now;//创建时间
                P1.create_user = tmpUser.user_name;//创建人
                P1.begin_time = DateTime.Now;//异常开始时间
                Db.Insertable(P1).ExecuteCommand();
            }

            MessageBox.Show("检验单已保存！");
            txtProdNumber.Text = "";
            CBONotGood.Text = "";
            textBox1.Text = "";
            label4.Text = "";
            ProdNumber.Text = "";
            txtIPQCNumber.Text = "";
            txtIPQCNotNumber.Text = "";
            textUser.Text = "";
            txtNotGood.Text = "";
            textType.Text = "";
            textTM.Text = "";
            OrderNumber.Text = "";
            comboBox1.Text = "无异常";
            //for (int i = 0; i < IPQCXMNumber; i++)
            //{
            //    TextBox txt = panel3.Controls["txt" + i] as TextBox;
            //    QCDetail qcDetail = new QCDetail();
            //    qcDetail.inspect_no = InspectNo;
            //    qcDetail.qc_name = listDetail[i].Name;
            //    qcDetail.qc_value = listDetail[i].Value;
            //    qcDetail.create_date = DateTime.Now;
            //    qcDetail.create_user = tmpUser.user_name;
            //    Db.Insertable(qcDetail).ExecuteCommand();
            //    txt.Text = "";
            //}



            for (int i = 0; i < DataSource.Items.Count; i++)
            {
                QCDetail qcDetail = new QCDetail();
                qcDetail.inspect_no = InspectNo;
                qcDetail.qc_name = DataSource.Items[i].Name;
                qcDetail.qc_value = DataSource.Items[i].Value;
                qcDetail.create_date = DateTime.Now;
                qcDetail.create_user = tmpUser.user_name;
                Db.Insertable(qcDetail).ExecuteCommand();
            }
            DataTable dataTable = (DataTable)listView1.DataSource;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                dataTable.Rows[i]["Value"] = DBNull.Value; // 或者可以使用 null
                var item = DataSource.Items.FirstOrDefault(d => d.Name == dataTable.Rows[i]["qc_name"].ToString());
                if (item != null)
                {
                    item.Value = "";
                }
            }

            // 重新绑定数据源以更新 ListView
            listView1.Rows.Clear();
            listView1.DataSource = dataTable; // 重新绑定数据源 
            listView1.DataBind();
        }
        /// <summary>
        /// 临时项目类
        /// </summary>
        private class Dateil
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }

        private void listView1_TemplateItemEvent(object sender, TemplateItemEventArgs e)
        {
            // 假设你在 ListView 中有一个 TextBox 控件  
        }
    }
}